﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;

namespace Spider.Data
{
    public static class Extension
    {
        public static IList<dynamic> ToList(this IDataReader reader)
        {
            if (!reader.IsClosed)
            {
                List<dynamic> lst = new List<dynamic>();
                using (reader)
                {
                    while (reader.Read())
                    {
                        dynamic obj = new SmartObject();
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            string name = reader.GetName(i);
                            object value = reader.GetValue(i);
                            obj[name] = value == DBNull.Value ? null : value;
                        }
                        lst.Add(obj);
                    }
                }
                return lst;
            }
            return null;
        }
        public static IList<dynamic> ToList(this DataTable datatable)
        {
            if (datatable.Rows != null && datatable.Rows.Count > 0)
            {
                DataColumnCollection columns = datatable.Columns;
                List<dynamic> lst = new List<dynamic>();
                for (int i = 0; i < datatable.Rows.Count; i++)
                {
                    dynamic obj = new SmartObject();
                    DataRow dr = datatable.Rows[i];
                    for (int j = 0; j < columns.Count; j++)
                    {
                        string name = columns[j].ColumnName;
                        object value = dr[j];
                        obj[name] = value == DBNull.Value ? null : value;
                    }
                    lst.Add(obj);
                }
                return lst;
            }
            return null;
        }
        public static IList<dynamic> ExecuteList(this IDbCommand command)
        {
            IDataReader dr = command.ExecuteReader();
            return dr.ToList();
        }
        public static IDbDataParameter GetDbParameter(this IDataParameterCollection parameters, string name)
        {
            return parameters[name] as IDbDataParameter;
        }
        public static IDbDataParameter GetDbParameter(this IDataParameterCollection parameters, int index)
        {
            return parameters[index] as IDbDataParameter;
        }

        public static IDataParameterCollection Add(this IDataParameterCollection parameters, IDbDataParameter parameter)
        {
            parameters.Add(parameter);
            return parameters;
        }
    }
}
